﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using System.Threading;
using System.Windows.Controls.Primitives;
using System.Text;
using SilverlightDesktop.Controls;
using VAdvantage.DataService;
using VAdvantage.Utility;
using VAdvantage.Classes;
using VAdvantage.Controls;

namespace VAdvantage.Panels
{
    public interface IStartMenuTree
    {
        void ItemClick(VTreeNode node);
        void ItemRightClick(VTreeNode node,bool isFavorite);
        void ItemRightClick(VTreeNode node,VTreeNode.ContextEventType e);
        void ItemContextEvent(VTreeNode node,bool isClosed);
    }


    public partial class StartPanel : UserControl, IStartMenuTree
    {
        private int _windowNo;
        private bool _hasBar;
        private bool _editable;
        private int _AD_Tree_ID;

        private List<SearchItem> leafNodesList = null;
        private List<VTreeNode> favoriteNodesList = null;

        private Explorer _explorer = null;
        private IHost _host = null;
        
        public StartPanel()
        {
            InitializeComponent();
        }

        public int AD_Tree_ID 
        {
            get {return AD_Tree_ID;}
            set { _AD_Tree_ID = value; }
            
        }
       
        public StartPanel(int WindowNo, bool hasBar, bool editable,IHost host)
            : this()
        {
            _windowNo = WindowNo;
            _hasBar = hasBar;
            _editable = editable;
            _explorer = host.GetExplorer;
            _host = host;
        }

        public StartPanel(int WindowNo, bool hasBar, bool editable)
            : this()
        {
            _windowNo = WindowNo;
            _hasBar = hasBar;
            _editable = editable;
        }

        public void InitMenu(int AD_Tree_ID)
        {
            _AD_Tree_ID = AD_Tree_ID;
            StartInitTreeProcess();
        }

        private void StartInitTreeProcess()
        {
            new System.Threading.Thread(new ThreadStart(delegate
                {
                    MTree vTree = new MTree(Utility.Envs.GetCtx(), _AD_Tree_ID, false, true, null);
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GetResponse(vTree));

                })).Start();
        }

      



        public void GetResponse(MTree o1)
        {
            

            if (o1.PrepareNodes(this))
            {
                TreeViewItem root = o1.GetRootNode();
                favoriteNodesList = o1.GetBarNodes();
                leafNodesList = o1.GetLeafNodes();
                this.treeView.Items.Add(root);
                FillFavoriteTree();
                _host.ShowBusyIndicator = false;
                _host.OnMenuLoad();
            }
        }

        private void FillFavoriteTree()
        {
            if (favoriteNodesList.Count > 0)
            {
                //TreeViewItem item = (TreeViewItem)favoriteNodesList[0];
                //item.Header = "sdsdsds";
                //treeFavorite.Items.Add(item);
                //item = new TreeViewItem();
                //item.Header = "ssdsd";
                //treeFavorite.Items.Add(item);
                for (int i = 0; i < favoriteNodesList.Count; i++)
                    treeFavorite.Items.Add((TreeViewItem)favoriteNodesList[i]);
               // treeFavorite.ItemsSource = favoriteNodesList;
            }

            if (leafNodesList.Count > 0)
            {
                txtSearch.ItemsSource = leafNodesList;
            }

        }

        public void ItemClick(VTreeNode node)
        {
         
            StartItem(node.Node_ID,node.SetName);
        }


        

        private void IsOpen(bool isOpen)
        {
            if (_explorer != null)
            {
                _explorer.IsStartMenuOpen = isOpen;
            }
            
            //_popupHost.IsOpen = isOpen;

        }

        private void rightPaneSiazeChanged(object sender, SizeChangedEventArgs e)
        {
            treeFavorite.Height = this.Height - 40;
        }

        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (txtSearch.IsDropDownOpen)
            //    return;
            //SearchItem item = (SearchItem) txtSearch.SelectedItem;


        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && txtSearch.SelectedItem !=null)
            {
                int id = ((SearchItem)txtSearch.SelectedItem).ID;
                String name = ((SearchItem)txtSearch.SelectedItem).Name;
                SetSerachText();
                txtSearch.IsDropDownOpen = false;
                StartItem(id,name);
                
            }
        }

        private void StartItem(int id,String name)
        {
            IsOpen(false);
            new Apps.AMenuStartItem(id, true, name, _host).Start();
        }

        private void stack_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (txtSearch.SelectedItem != null)
            {
                int id = ((SearchItem)txtSearch.SelectedItem).ID;
                String name = ((SearchItem)txtSearch.SelectedItem).Name;
                _isMouseDown = false;
                SetSerachText();
                StartItem(id,name);
                
            }
        }

        private bool _isMouseDown = false;
        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _isMouseDown = true;
            //if (((Control)sender).Tag != null)
            //{
            //    int id = Convert.ToInt32(((Control)sender).Tag);


            //}


        }

        private void SetSerachText()
        {
            txtSearch.Text = "Search";
        }

        private void txtSearch_Focus(object sender, RoutedEventArgs e)
        {
            txtSearch.Text = "";
        }

        private void txtSearch_LostFocus(object sender, RoutedEventArgs e)
        {
            if(_isMouseDown)
            {
                _isMouseDown = false;
                return;
            }
            SetSerachText();
        }



        public void ItemRightClick(VTreeNode node, bool isFavorite)
        {
            if (isFavorite)
            {
                BarDBupdate(false, node.Node_ID);
                UpdateNodeBarStatus(node.Node_ID, false);
                treeFavorite.Items.Remove(node);
                node = null;
            }
            else
            {
                BarDBupdate(true, node.Node_ID);
                node.OnBar = true;
                VTreeNode favNode = new VTreeNode(node, true, false, this);
                treeFavorite.Items.Add(favNode);

                ////add the new node in favorite list
                try
                {
                    favoriteNodesList.Add(favNode);
                }
                catch { }

            }

            //MessageBox.Show(isFavorite.ToString());
            //IsOpen(false);
        }
        public bool BarDBupdate(bool add, int Node_ID)
        {
            int AD_Client_ID = Utility.Envs.GetContext().GetAD_Client_ID();
            int AD_Org_ID = Utility.Envs.GetContext().GetAD_Org_ID();
            int AD_User_ID = Utility.Envs.GetContext().GetAD_User_ID();
            StringBuilder sql = new StringBuilder();
            if (add)
            {
                sql.Append("INSERT INTO AD_TreeBar "
                    + "(AD_Tree_ID,AD_User_ID,Node_ID, "
                    + "AD_Client_ID,AD_Org_ID, "
                    + "IsActive,Created,CreatedBy,Updated,UpdatedBy)VALUES (")
                    .Append(_AD_Tree_ID).Append(",").Append(AD_User_ID).Append(",").Append(Node_ID).Append(",")
                    .Append(AD_Client_ID).Append(",").Append(AD_Org_ID).Append(",")
                    .Append("'Y',SysDate,").Append(AD_User_ID).Append(",SysDate,").Append(AD_User_ID).Append(")");
                //	if already exist, will result in ORA-00001: unique constraint 
            }
            else
            {
                sql.Append("DELETE FROM AD_TreeBar WHERE AD_Tree_ID=").Append(_AD_Tree_ID)
                    .Append(" AND AD_User_ID=").Append(AD_User_ID)
                    .Append(" AND Node_ID=").Append(Node_ID);
                //sql.Append("DELETE FROM AD_TreeBar WHERE ")
                //  .Append("  AD_User_ID=").Append(AD_User_ID)
                //  .Append(" AND Node_ID=").Append(Node_ID);
               
            }
           var client = Utility.AEnv.GetDataServiceClient();

            client.SetDataXMLCompleted +=(sender,e) =>
            {
                string s = e.Result;
            };
            client.SetDataXMLAsync(sql.ToString());
            client.CloseAsync();
            //int no = DataBase.DB.ExecuteQuery(sql.ToString(), null);
            return true;
        }


        private void UpdateNodeBarStatus(int id, bool onBar)
        {
            System.Collections.IEnumerator en;
            bool found = false;

            VTreeNode root =  (VTreeNode)treeView.Items[0];

            for (int i = 0; i < root.Items.Count; i++)
            {
                VTreeNode item = (VTreeNode)root.Items[i];

                if (item.Node_ID == id)
                {
                    item.OnBar = onBar;
                    found = true;
                }

                en = item.preorderEnumeration();

                while (en.MoveNext())
                {
                    Object current = en.Current;
                    if (current == null)
                    {
                        continue;
                    }
                    else if (current is VTreeNode)
                    {
                        if (((VTreeNode)current).Node_ID == id)
                        {
                            ((VTreeNode)current).OnBar = onBar;
                            found = true;
                            break;
                        }
                    }
                }
                if (found)
                {
                    break;
                }
            }
        }

        private void logOut_Click(object sender, RoutedEventArgs e)
        {

            VAdvantage.Framework.Message msg = VAdvantage.Classes.ShowMessage.AskMessage("Logout", true, "");
            msg.Closed += (s, ee) =>
                {
                    if (msg.DialogResult != null && (bool)msg.DialogResult)
                    {
                        UnLoadMenuItems();


                        //log.Info("Application Logged out");
                        //	End Session
                        try
                        {
                            //CloseMailBoxObject();

                            //


                            //RemoveControl(null, true);

                            //SetControlsAndTitle(true);

                            Envs.LogOut();
                            AEnv.Reset();
                             this.Dispatcher.BeginInvoke(delegate
                             {
                                 App app = (App)Application.Current;
                                 app.GoToPage(new MainPage());
                             });

                                
                            //this.Close(

                            //VLogin login = new VLogin(this);
                            //login.ShowDialog(this);

                            //SetControlsAndTitle(false);
                            //login.Dispose();
                        }
                        catch
                        {

                        }
                    }
                };

              //if (ask)
              //{
              //}

            //System.Windows.Browser.HtmlPage.Document.Submit();
            //MessageBox.Show("Log out Process");
            //System.Windows.Browser.HtmlPage.Document.InvokeSelf();
           // System.Windows.Browser.HtmlPage.Window.Invoke("reload");

            //MainPage m = new MainPage();
           // m.FontFamily = new System.Windows.Media.FontFamily("/VAdvantage;component/Fonts/Ubuntu-Regular.ttf#Ubuntu");
           // VAdvantage.App.Current.RootVisual = m;
            //((MainPage)this.RootVisual).FontFamily = 
            
        }

        public void UnLoadMenuItems()
        {

            //treeView.Items.Clear();
            //treeFavorite.Items.Clear();
            //txtSearch.ItemsSource = null;
        }




        public void ItemRightClick(VTreeNode node, VTreeNode.ContextEventType e)
        {
            //throw new NotImplementedException();
        }


       


        public void ItemContextEvent(VTreeNode node, bool isClosed)
        {
            //throw new NotImplementedException();
        }

        public List<VTreeNode> GetFavoriteNode()
        {
            return favoriteNodesList;
        }
       
    }
}
